package cn.com.zero.common.auth.security.handler;

import cn.com.zero.api.auth.constant.HttpHeaderConstants;
import cn.com.zero.common.auth.constant.SecurityConstants;
import cn.com.zero.common.auth.security.service.AbstractLoginAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xiongxj
 * @version 1.0.0
 * @Description 自定义 退出成功后的 处理类
 * @createTime 2023/3/24 15:03
 */
@Component
public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {
    private AbstractLoginAuthenticationService loginAuthenticationService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 注意，由于不再使用session，SecurityContextHolder中不再存储context 此处authentication为null

        // 获取登录设备和登录IP
        String loginDevice = request.getHeader(HttpHeaderConstants.LOGIN_DEVICE_HEADER);
        // 从token中获取当前用户信息
        String token = request.getHeader(HttpHeaderConstants.TOKEN_HEADER);

        // 退出成处理逻辑（可以写退出成功的日志）
        loginAuthenticationService.logoutHandler(token, loginDevice);

        request.getRequestDispatcher(SecurityConstants.SECURITY_CONTROLLER_PATH + "/logoutSuccessHandler").forward(request, response);
    }

    @Autowired
    public void setLoginAuthenticationService(AbstractLoginAuthenticationService loginAuthenticationService) {
        this.loginAuthenticationService = loginAuthenticationService;
    }
}
